﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;
using System.Collections.ObjectModel;

namespace eLearning.View
{
    public partial class LoginPage : PhoneApplicationPage
    {
        public static User.UserType userType { get; set; }

        public LoginPage()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("Anda ingin Keluar?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                App.Quit();
            }
            else
            {
                e.Cancel = true;
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            //load user yg tersimpan di memory
            User user = SavedUser.Instance.LoadUser();

            if (user != null)
            {
                textBoxNoInduk.Text = user.IdUser;
                //textBoxUsername.Text = user.Username;
                if (!string.IsNullOrEmpty(user.Password) && user.Saved)
                {
                    passwordBox.Password = user.Password;
                    savePasswordCheckBox.IsChecked = user.Saved;
                }
                userType = user.Type;
            }
            SavedUser.Instance.SetUser(null);

            if (userType == User.UserType.Dosen || userType == User.UserType.Admin)
                checkDosen.IsChecked = true;
            else
                checkMahasiswa.IsChecked = true;

        }
        
        //link page registrasi
        private void hyperlinkRegistration_Click(object sender, RoutedEventArgs e)
        {
            Utility.GotoPage(this,"/View/RegistrationPage.xaml");
        }

        //event login
        private void buttonLogin_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxNoInduk.Text.Length < 1)
            {
                MessageBox.Show("NIM/NIP can't empty!");
                textBoxNoInduk.Focus();
                return;
            }
            /*if (textBoxUsername.Text.Length < 1)
            {
                MessageBox.Show("Username can't empty!");
                textBoxUsername.Focus();
                return;
            }*/
            if (passwordBox.Password.Length < 1)
            {
                MessageBox.Show("Password can't empty!");
                passwordBox.Focus();
                return;
            }

            //call proses login
            LoginUser();
        }

        private void LoginUser()
        {    
            string url = "";
            string json = "";

            //sebagai mahasiswa
            if (checkMahasiswa.IsChecked == true)
            {
                //membuat objek mahasiswa yg akan login
                Mahasiswa mahasiswa = new Mahasiswa();
                mahasiswa.Nim = textBoxNoInduk.Text;
                //mahasiswa.Username = textBoxUsername.Text;
                mahasiswa.Password = passwordBox.Password;

                //serialisasi objek mahasiswa ke Json
                json = JsonConvert.SerializeObject(mahasiswa);
                url = Config.Instance.MHS_SERVICE_URL() + Config.LOGIN_ACTION_KEY;
            }
            //sebagai dosen
            else if (checkDosen.IsChecked == true)
            {
                Dosen dosen = new Dosen();
                dosen.Nip = textBoxNoInduk.Text;
                //dosen.Username = textBoxUsername.Text;
                dosen.Password = passwordBox.Password;

                json = JsonConvert.SerializeObject(dosen);
                url = Config.Instance.DOSEN_SERVICE_URL() + Config.LOGIN_ACTION_KEY;
            }

            LoginProcess(url, json);
            progressBar.Visibility = Visibility.Visible;
        }

        //proses login
        private void LoginProcess(string url, string json)
        {            
            //deklarasi akses web service
            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            //Set header
            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            //menangani respon yang diberikan oleh server ketika menjalankan method UploadStringAsync()
            client.UploadStringCompleted += new UploadStringCompletedEventHandler(login_UploadStringCompleted);

            try
            {
                //melakukan UploadString dengan method POST secara asynchronous
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }
        
        //menangkap respon dari server
        private void login_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                ObservableCollection<UserLogin> loginUser = JsonConvert.DeserializeObject<ObservableCollection<UserLogin>>(e.Result);
                if (loginUser != null)
                {
                    if (loginUser.Count > 0 && loginUser[0].Status.Contains("Success"))
                    {
                        if (loginUser[0].LoginUser.Type == User.UserType.Mahasiswa)
                            Utility.GotoPage(this, "/View/Mahasiswa/DashboardPage.xaml");
                        else if (loginUser[0].LoginUser.Type == User.UserType.Dosen ||
                                loginUser[0].LoginUser.Type == User.UserType.Admin)
                            Utility.GotoPage(this, "/View/Dosen/DashboardPage.xaml");

                        SaveUserLogin(loginUser[0].LoginUser);
                        //MessageBox.Show("Message : " + loginUser[0].Status);                    
                    }
                    else
                    {
                        MessageBox.Show(loginUser[0].Status);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
            progressBar.Visibility = Visibility.Collapsed;
        }

        //menyimpan user yg login ke memory / login cache
        private void SaveUserLogin(User user)
        {
            if (user != null)
            {
                user.IdUser = textBoxNoInduk.Text;
                //user.Username = textBoxUsername.Text;
                if (savePasswordCheckBox.IsChecked == true)
                {
                    user.Saved = true;
                    user.Password = passwordBox.Password;
                }
                else
                {
                    user.Saved = false;
                    user.Password = "";
                }
                /*if (checkMahasiswa.IsChecked == true)
                    user.Type = User.UserType.Mahasiswa;
                else
                    user.Type = User.UserType.Dosen;
                */
                SavedUser.Instance.SetUser(user);
            }
        }

        private void mahasiswa_Checked(object sender, RoutedEventArgs e)
        {
            if (textBlockNoInduk != null)
                textBlockNoInduk.Text = "NIM";
        }

        private void dosen_Checked(object sender, RoutedEventArgs e)
        {
            if (textBlockNoInduk != null)
                textBlockNoInduk.Text = "NIP";
        }

        private void SettingMenu_Click(object sender, EventArgs e)
        {
            Utility.GotoPage(this, "/View/ConfigPage.xaml");
        }

    }
}